<template>
    <div  class="search-suggestion-container">
        <van-cell 
        :title="suggestion" 
        icon="search" 
        v-for="(suggestion,index) in searchSuggestionList" 
        :key="index" 
        @click = "$emit('search',suggestion)"
        >
        <div slot="title" v-html="highLight(suggestion)"></div>
        </van-cell>
    </div>
</template>
<script>
import { getSearchSuggestion } from '@/api/search'
import { debounce } from 'lodash'
export default {
    name: 'SearchSuggestion',
    props: {
      searchText: {
          type: String,
          require: true
      }
    },
    data() {
        return {
            searchSuggestionList: []
        };
    },
    watch: {
        searchText: {
             // 处理防抖
             handler: debounce(async function () {
                // console.log('hello');
                const { data} = await getSearchSuggestion(this.searchText)
                const { data:{options} } = data
                this.searchSuggestionList = options[0] ? options : []
            },500),
            immediate: true
        }
    },
    mounted() {
        
    },

    methods: {
      highLight (str) {
          //正则表达式中间的内容会作为字符串处理
          // 这里采用实例化正则的方法，传入需要匹配的变量
          const reg = new RegExp(this.searchText, 'gi')
          return str.replace(reg, `<span style="color:red">${this.searchText}</span>`)
      },
      // 点击联想建议，跳转至搜索结果页
    //   searchResult (suggestion) {
    //       console.log(suggestion);
    //       this.$emit('setSearchText', suggestion);
    //   }
    },
};
</script>

<style lang="less" scoped>

</style>